<?php
/**
 * Created by PhpStorm.
 * User: Knight
 * Date: 2018/10/23
 * Time: 18:24
 */

namespace app\api\service;


use app\api\util\RandStr;
use app\api\exception\WxException;
use app\api\util\JwtUtil;
use app\api\util\RedisUtil;
use app\api\util\wechat\WXBizDataCrypt;
use app\api\util\WxApi;

use app\api\model\WxUser as WxUserModel;
use app\api\service\Step as StepService;
use think\Cache;
use think\Log;
use think\Request;

class Index
{

    /**
     * 通过code换取openid及unionid,返回session_key,openid
     * @return  code  1:未进入过小程序  0:已进入小程序
     */
    public function codeToOpneid($code)
    {
        $wxapi = new WxApi();
        $wxArr = json_decode($wxapi->code2Session($code), true);
        Log::info('--------------授权信息2:'.json_encode($wxArr));
        if (empty($wxArr)||array_key_exists('errcode', $wxArr)) {//判断参数是否错误
            Log::error('--------------授权错误2:'.json_encode($wxArr));
            throw new WxException(['msg'=>'参数错误']);
        }

        $wxUserModel = new WxUserModel();
        $wxUser = $wxUserModel->where('openid', $wxArr['openid'])->find();
        if(empty($wxUser)){
            //未进入过小程序
            return ['code'=>1,'data'=>$wxArr];
        }

        //已进入过小程序
        $unionid=$wxUser['unionid'];
        $token=$this->getIndexParam($unionid);
        return ['code'=>0,'data'=>['token'=>$token,'session_key'=>$wxArr['session_key']]];

    }

    /**
     * 初始化获取参数
     * @param $unionid
     * @return array
     */
    protected function getIndexParam($unionid){
        //返回加密token
        $token = JwtUtil::jwtEncode(['unionid' => $unionid]);
        return $token;

    }


    /**
     * 通过encryptedData,iv,openid,session_key解密获取unionid
     */
    public function getToken($params)
    {
        $appid=config('APPID');
        $sessionKey=$params['sessionkey'];
        $encryptedData=$params['encrypteddata'];
        $iv=$params['iv'];
        $pc=new WXBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data );
        if ($errCode == 0) {//解密成功
            $data=json_decode($data,true);
            $wxUserModel = new WxUserModel();
            if(array_key_exists('unionId',$data)){

            }
            $wxuser=$wxUserModel->where('unionid',$data['unionId'])->find();
            if(empty($wxuser)){
                $imgurl=$this->userIconSave($data['avatarUrl']);
//                //新增
                $wxuser=[
                    'openid'=>$data['openId'],
                    'unionid'=>$data['unionId'],
                    'nickName'=>base64_encode($data['nickName']),
                    'avatarUrl'=>$imgurl,
                    'gender'=>$data['gender'],
                    'created_time'=>date('Y-m-d H:i:s')
                ];
                $stepService=new StepService();
                $stepService->initData($data['unionId'],$wxuser);//初始化用户数据(用户点亮城市,用户步数,用户当日签到,用户可抽奖次数)
            }else{
                if(empty($wxuser['avatarUrl'])||empty($wxuser['openid'])){
                    $imgurl=$this->userIconSave($data['avatarUrl']);
                    $wxuser->nickName=base64_encode($data['nickName']);
                    $wxuser->openid=$data['openId'];
                    $wxuser->avatarUrl=$imgurl;
                    $wxuser->gender=$data['gender'];
                    $wxuser->save();
                }
            }
            $token=$this->getIndexParam($data['unionId']);
            return ['code'=>1,'token'=>$token];
        } else {//解密失败
            throw new WxException(['msg'=>'加密参数错误']);
        }
    }





    /**
     * 保存头像
     * @param $url
     * @return string
     */
    protected  function userIconSave($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER,0);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        $file = curl_exec($ch);
        curl_close($ch);
        $randStr = (new RandStr())->GetRandStr(10);
        $name = strval($randStr) . strval(time());

        $resource = fopen('E:\Apache24\htdocs\img\wximg' . DS . $name . ".jpg", 'a');
        fwrite($resource, $file);
        fclose($resource);
        $uri = config('uri');
        return $uri . '/img/wximg/' . $name . '.jpg';
    }






    /**
     * 通过code换取openid及unionid,并保存
     */
    public function index($code)
    {
        $wxapi = new WxApi();
        $wxArr = json_decode($wxapi->code2Session($code), true);
        Log::info('--------------授权信息:'.json_encode($wxArr));
        if (empty($wxArr)||array_key_exists('errcode', $wxArr)||!array_key_exists('unionid', $wxArr)) {//判断参数是否错误
            Log::error('--------------授权错误:'.json_encode($wxArr));
            throw new WxException(['msg'=>'unionid参数未获取到']);
        }
        $wxUserModel = new WxUserModel();
        $wxUserModel = $wxUserModel->where('unionid', $wxArr['unionid'])->find();
        if(empty($wxUserModel)){
            $wxUserModel=new WxUserModel();
            $wxUserModel->openid = $wxArr['openid'];
            $wxUserModel->unionid = $wxArr['unionid'];
            $wxUserModel->save();
        }
        return $wxArr['unionid'];

    }

    /**
     * 保存微信用户昵称头像等信息
     * @param $unionid
     * @param $params
     */
    public function saveWxUserInfo($unionid, $params)
    {
        $wxUserModel = new WxUserModel();
        $wxUser = $wxUserModel->where('unionid', $unionid)->find();
        if(!$wxUser){
            throw new WxException();
        }
        if(array_key_exists('nickName',$params)){
            $wxUser->nickName=$params['nickName'];
        }
        if(array_key_exists('avatarUrl',$params)){
            $wxUser->avatarUrl=$params['avatarUrl'];
        }
        if(array_key_exists('gender',$params)){
            $wxUser->gender=$params['gender'];
        }
        if(array_key_exists('province',$params)){
            $wxUser->province=$params['province'];
        }
        if(array_key_exists('city',$params)){
            $wxUser->city=$params['city'];
        }
        if(array_key_exists('country',$params)){
            $wxUser->country=$params['country'];
        }
        $wxUser->save();
    }

}